//
//  TextUtil.swift
//  UserApp_iOS
//
//  Created by linlin on 2019/9/10.
//  Copyright © 2019 linlin. All rights reserved.
//

import Foundation

extension String {
    var charactersArray: [Character] {
        return Array(self)
    }
    
    func isMobilePhone() -> Bool{        
        return self.match(regexPattern: "^0?(13|15|18|14|17|19|16)[0-9]{9}$")
    }
    
    func isVinNumber() -> Bool {
        let pattern = "^[A-Z\\d]{17}$"
        let vinStr = self.trimmingCharacters(in: .whitespaces)
        
        return vinStr.match(regexPattern: pattern)
    }
    
    func getQueryValue(key: String) -> String {
        let temp = self.components(separatedBy: key+"=")
        var value: String = ""
        if temp.count > 1 {
            let temp1 = temp[temp.count-1].components(separatedBy: "&")
            if temp.count > 0 {
                value = temp1[0]
            }
        }
        
        return value
    }
    
    func match(regexPattern: String) -> Bool {
        do {
            let regex = try NSRegularExpression(pattern: regexPattern, options: [])
            let result = regex.matches(in: self, options: [], range: NSRange(location: 0, length: self.count))
            if result.count > 0{
                return true
            }
        } catch let error {
            print(error)
        }
        
        return false
    }
}

extension Date {
    var formatDate: String{
        let dateFormatter: DateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"
        return dateFormatter.string(from: self)
    }
}
